package pro4;
import java.io.*;
import java.nio.file.*;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/Ans4/AddProductServlet")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 1, // 1MB
        maxFileSize = 1024 * 1024 * 10,      // 10MB
        maxRequestSize = 1024 * 1024 * 15   // 15MB
)
public class AddProductServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        // 获取表单字段
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        double price = Double.parseDouble(request.getParameter("price"));
        int stock = Integer.parseInt(request.getParameter("stock"));
        // 获取上传的图片
        Part filePart = request.getPart("image");
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();

        // 如果没有选择文件，则使用默认图片
        if (fileName == null || fileName.isEmpty()) {
            fileName = "default.jpg";
        }
        // 设置上传路径（相对于当前项目的根目录）
        String uploadPath = getServletContext().getRealPath("") + File.separator + "uploads";

        // 创建 uploads 文件夹（如果不存在）
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        // 构建文件写入路径
        String filePath = uploadPath + File.separator + fileName;
        // 写入服务器磁盘
        filePart.write(filePath);
        // 构造数据库中存储的 URL 路径
        String imageUrl = "uploads/" + fileName;
        // 插入商品信息到数据库
        ProductDAO dao = null;
        try {
            dao = new ProductDAO();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            dao.addProduct(id, name, price, stock, imageUrl);
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "商品添加失败，请重试");
            request.getRequestDispatcher("/Ans4/error.jsp").forward(request, response);
            return;
        }
        // 成功后跳转回商品管理页面
        response.sendRedirect(request.getContextPath() + "/Ans4/product_management.jsp");
    }
}
